<?php

class OrderManageController extends Controller
{

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(

            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('nextauction','getlist','publish','cancel'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }


	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}

    public function actionUpdateStatus($oid,$status=_ORDER_STATE_CONFIRM) {
        if ($status==_ORDER_STATE_CONFIRM) {


        }

    }
    /**
     * 获得订单列表
     */
    public function actionGetList($iDisplayStart=0,$iDisplayLength=10,$search_name="",$search_code="")
    {
        $resultColumn = array('number');
        $query = array(
            'conditions' => array(
                'status'=>array('=='=>2),
                // 'number'=>array('=='=>new MongoRegex("/^{$search_code}/i")),
               // 'channel'=>array('=='=>constant("channel_homepage"))
            ),
            'select'=>$resultColumn,
            'limit'=>$iDisplayLength,
            'offset'=>$iDisplayStart,
        );

        $result = Order::model()->findAll($query);

      
        $records = array();
        $records["aaData"] = array(); 

        if(!empty($result))
            foreach ($result as $key => $value) {
                $tmp = array();
                $value->_id = (string)$value->_id;

                foreach ($value as $key1=>$value1) {
                    if(in_array($key1, $resultColumn))
                    {
                        array_push($tmp, $value1);
                    }
                }

            array_push($tmp, '<a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs red btn-removable"><i class="fa fa-times"></i> 已经发货待确认</a> 
                 <a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs yellow btn-down"><i class="fa fa-times"></i> 取消</a> 
                  ');

                array_push($records["aaData"], $tmp);
            }

        $records["iTotalRecords"] = Order::model()->count($query);
        $records["iTotalDisplayRecords"] = Order::model()->count($query);
  
        echo json_encode($records);
    }

    public function actionPublish($id)
    {
        $order = Order::model()->findByPk(new MongoId($id));
        $order->status = 3;
        $order->save(false);
    }

    public function actionCancel($id)
    {
        $order = Order::model()->findByPk(new MongoId($id));
        $order->status = 5;
        $order->save(false);
    }


    /**
     * 启动新一轮拍卖
     * @param $gid
     * @param $oauction
     */
    private function setNextAuction($gid) {
        try {
            RedisCacheUtil::lock($gid);

            $flowcode = $this->updateAndNextcode($gid);
            if ($flowcode=='-1') return false;
            //设置上一次商品竞拍为零
            //处理下一次竞拍
            $goods = Goods::model()->findByPk(new MongoId($gid));
            $goods->inventory = (int)$goods->inventory -1;
            //确认发货，该商品库存需要减Ω
            try {
                if ($goods->inventory==0) {
                    $goods->$selling =false;
                    $goods->save(false);
                    return false;
                }
            } catch(Exception $ex) {
                Yii::getLogger()->log($ex->getMessage());
                Yii::getLogger()->log("执行setNextAuction方法商品下架失败，商品Id=".$gid,LOG_INFO);
                return false;
            }
            try {
                $goods->save(false);
            } catch(Exception $ex) {
                Yii::getLogger()->log($ex->getMessage());
                Yii::getLogger()->log("执行setNextAuction方法将商品库存数-1失败，商品Id=".$gid,LOG_INFO);
                return false;
            }
            try {
                $auction = new GoodsAuctioninfo();
                $auction->starttime=time();
                $auction->createtime = $auction->starttime;
                $auction->endtime = $auction->starttime+(int)$goods->autiontime;
                $auction->state = _GOODS_AUCTION_STATE_PROCESS;
                $auction->goods = $gid;
                $auction->flowcode = $flowcode;
                $auction->save(flase);
            } catch(Exception $ex) {
                Yii::getLogger()->log($ex->getMessage());
                Yii::getLogger()->log("执行setNextAuction方法创建GoodsAuctioninfo失败，Auction=".json_encode($auction),LOG_INFO);
                return false;
            }
        } catch(Exception $ex) {
            Yii::getLogger()->log($ex->getMessage());
        } finally {
            RedisCacheUtil::unlock($gid);
        }
        return true;
    }

    /**
     * @param $flowcode
     * @return string
     */
    private function updateAndNextcode($gid) {
        try {
            $query['limit'] = 1;
            $query['sort'] = array('flowcode'=>EMongoCriteria::SORT_DESC);
            $query['conditions'] = array('goods'=>array('=='=>(string)$gid));
            $auction = GoodsAuctioninfo::model()->find();
            $auction->state = _GOODS_AUCTION_STATE_TRANSACTION;

            $fields = preg_split("/-/",$auction->flowcode);
            $value = (int)$fields[1] + 1;
            $auction->update();
            return $fields[0].$value;
        } catch(Exception $ex) {
            Yii::getLogger()->log($ex->getMessage());
            Yii::getLogger()->log("执行updateAndNextcode方法变更GoodsAuctioninfo状态失败，Auction=".json_encode($auction),LOG_INFO);
            return '-1';
        }
    }
}